package MountainMq.sender;

import MountainMq.po.TransMessagePO;
import MountainMq.service.TransMessageService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class TransMessageSender {
    @Autowired(required = false)
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private TransMessageService transMessageService;
    @Autowired
    private ObjectMapper mapper;

    public void send(String exchange,String routingKey,Object payload){
        log.info("send()：exchange:{} routingKey:{} payload:{}",exchange,routingKey,payload);
        try{
            String payloadStr = mapper.writeValueAsString(payload);
            // 发消息之前先存数据库
            TransMessagePO transMessagePO = transMessageService.messageSendReady(exchange, routingKey, payloadStr);
            MessageProperties messageProperties = new MessageProperties();
            messageProperties.setContentType("application/json");
//            messageProperties.setMessageId(transMessagePO.getId());
            Message message = new Message(payloadStr.getBytes(),messageProperties);
            // 给消息本身也设置ID，因为在消息返回机制中，是没有correlationData参数的，那么就无法确认消息是谁了
            message.getMessageProperties().setMessageId(transMessagePO.getId());

            // 消息标识 通过这个数据我们就可以知道这些消息对应数据库中的ID，便于区分 用于消息确认回调
            CorrelationData correlationData = new CorrelationData(transMessagePO.getId());
            // 发消息
            rabbitTemplate.convertAndSend(exchange,routingKey,message,correlationData);
            log.info("message sent,ID:{}",transMessagePO.getId());
        }catch (Exception e){
            // 不要使用e.printStack... 这样不受日志管理
            // 使用log也不要使用加号，逗号分割就行了
            log.error(e.getMessage(),e);
        }
    }
}
